// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package watch_impl

import (
	"sync"

	"gitcode.com/openseaotter/so_agent/config"
	"gitcode.com/openseaotter/so_agent/utils"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

type WatchManager struct {
	logger     *zap.Logger
	runnerList []*WatchRunner
	lock       sync.Mutex
}

func NewWatchManager() *WatchManager {
	hook := lumberjack.Logger{
		Filename:   utils.LOG_FILE_PATH,
		LocalTime:  true,
		MaxSize:    100,
		MaxBackups: 30,
		MaxAge:     30,
		Compress:   false,
	}

	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "linenum",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
		EncodeName:     zapcore.FullNameEncoder,
	}

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.AddSync(&hook),
		zapcore.DebugLevel,
	)

	return &WatchManager{
		logger:     zap.New(core),
		runnerList: []*WatchRunner{},
	}
}

func (wm *WatchManager) Reload() error {
	cfg, err := config.ReadAgentConfigFromCache()
	if err != nil {
		return err
	}

	wm.lock.Lock()
	defer wm.lock.Unlock()

	//停止所有现有的runner
	for _, runner := range wm.runnerList {
		runner.Stop()
	}
	wm.runnerList = []*WatchRunner{}

	//启动新的runner
	for _, watchCfg := range cfg.WatchCfgList {
		runner := NewWatchRunner(cfg.MaxExecSecond, watchCfg, wm.logger)
		go runner.Run()
		wm.runnerList = append(wm.runnerList, runner)
	}
	return nil
}
